package com.sgb.kjwl.view.ui.activity.self.packers;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.ScreenUtils;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivitySelfTeamDeviceEditBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.self.SelfEmploymentEditEntity;
import com.sgb.kjwl.model.entity.self.SelfTeamDeviceEntity;
import com.sgb.kjwl.view.ui.activity.PhotoViewActivity;
import com.sgb.kjwl.view.ui.adapter.packers.NewTextAdapter;
import com.sgb.link.view.adapter.SelfTeamPicAdapter;
import com.sgb.kjwl.view.ui.adapter.self.packers.SelfTeamVideoAdapter;
import com.sgb.kjwl.viewmodel.self.packers.SelfTeamDeviceEditModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.MToast;

import java.io.File;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

/**
 * description:个人中心-自有设备
 * @author wangyajun
 * @date 2020/9/2
 */
public class SelfTeamDeviceEditActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {
    @Inject
    SelfTeamDeviceEditModel mModel;
    private ActivitySelfTeamDeviceEditBinding mBind;

    private String id;
    private SelfTeamDeviceEntity mEntity;
    /**
     * 设备照片
     */
    private SelfTeamPicAdapter mPicAdapter;
    /**
     * 证明照片
     */
    private SelfTeamPicAdapter mPicMaterAdapter;
    /**
     * 视频
     */
    private SelfTeamVideoAdapter mVideoAdapter;

    private List<String> mUploadImgList;
    /**
     * 防止重复上传
     */
    private Map<String, String> mCacheImgMap;
    private int mCurPicNum;

    private List<String> mUploadImgList2;
    /**防止重复上传
     *
     */
    private Map<String, String> mCacheImgMap2;
    private int mCurPicNum2;
    private List<String> mUploadVideoList;
    private boolean isDevicePic;
    private boolean isEmt;
    private NewTextAdapter mNewTextAdapter;

    public static void start(AppCompatActivity context, String id, int code) {
        Intent intent = new Intent();
        intent.setClass(context, SelfTeamDeviceEditActivity.class);
        intent.putExtra(AppConstant.EXTRA_ENTITY, id);
        context.startActivityForResult(intent, code);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder().appComponent(appComponent).selfModule(new SelfModule(this)).build().inject(this);
    }

    @Override
    protected boolean statusBarDark() {
        return false;
    }

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (TextUtils.isEmpty(id)) {
            mEntity = new SelfTeamDeviceEntity();
            mActionBar.setTitle(String.format("新增%s", getResources().getString(R.string.self_team2)));
        } else {
            mActionBar.setTitle(String.format("编辑%s", getResources().getString(R.string.self_team2)));
        }
    }

    @Override
    protected void initView() {
        id = getIntent().getStringExtra(AppConstant.EXTRA_ENTITY);
        mBind = DataBindingUtil.setContentView(this, R.layout.activity_self_team_device_edit);
        mBind.btnRelease.setOnClickListener(this);
        mBind.etName.setOnWholeItemClickListener(this);
        mBind.addBtn.setOnClickListener(this);
        mBind.etDeviceAge.setInfilterType(ItemInputTextView.TYPE_AGE);
        mBind.etPropertyState.setOnWholeItemClickListener(this);

        mCacheImgMap = new HashMap<>();
        mUploadImgList = new ArrayList<>();

        mCacheImgMap2 = new HashMap<>();
        mUploadImgList2 = new ArrayList<>();

        mUploadVideoList = new ArrayList<>();
        mBind.etModelNum.setNumberAndLetter("0123456789");
        //初始化数据
        if (mNewTextAdapter == null) {
            mNewTextAdapter = new NewTextAdapter(getActivity(), null);
        }
        mBind.desList.setAdapter(mNewTextAdapter);
        mBind.desList.setLayoutManager(new LinearLayoutManager(this));
        mNewTextAdapter.setOnClose(position -> {
            mNewTextAdapter.removeItem(position);
            if (mNewTextAdapter.getDatas().size() == 0) {
                mBind.desList.setVisibility(View.GONE);
            }
        });
        initPic();
        initPicMaterials();
        initVideo();
    }

    private void initPic() {
        GridLayoutManager manager = new GridLayoutManager(this, 4);
        mBind.rvPic.setLayoutManager(manager);
        mPicAdapter = new SelfTeamPicAdapter(this, new ArrayList<>(), AppConstant.UPLOAD_MAX_SIZE, manager);
        mBind.rvPic.setHasFixedSize(false);
        mBind.rvPic.addItemDecoration(new GridSpacingItemDecoration(5, ScreenUtils.dip2px(this, 2), false));
        mBind.rvPic.setAdapter(mPicAdapter);
        mPicAdapter.setOnItemClick(new AdapterOnItemClick<String>() {
            @Override
            public void onItemClick(String s, int position) {
                if (TextUtils.isEmpty(s)) {
                    isDevicePic = true;
                    mModel.pictureSelector(mPicAdapter.hasCount());
                } else {
                    Intent intent = new Intent(getActivity(), PhotoViewActivity.class);
                    intent.putExtra(PhotoViewActivity.KEY_PHOTO_URLS, (Serializable) mPicAdapter.getDatas());
                    intent.putExtra(PhotoViewActivity.KEY_PHOTO_POSITION, position);
                    startActivity(intent);
                }
            }
        });
    }


    private void showCourseTimePop() {
        Calendar dayCalendar = Calendar.getInstance();
        dayCalendar.setTime(new Date());
        TimePickerView timePicker = new TimePickerBuilder(this, (date, v) -> {
            @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(date);
            try {
                mBind.etDeviceAge.setContent(format);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).setType(new boolean[]{true, true, true, false, false, false})
                .setCancelText("取消").setSubCalSize(15)
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleText("请选择设备年限")
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD"))
                .build();
        timePicker.show();
    }

    private void initPicMaterials() {
        GridLayoutManager manager = new GridLayoutManager(this, 4);
        mBind.rvPiMaterials.setLayoutManager(manager);
        mPicMaterAdapter = new SelfTeamPicAdapter(this, new ArrayList<>(), AppConstant.UPLOAD_MAX_SIZE, manager);
        mBind.rvPiMaterials.setHasFixedSize(false);
        mBind.rvPiMaterials.addItemDecoration(new GridSpacingItemDecoration(5, ScreenUtils.dip2px(this, 2), false));
        mBind.rvPiMaterials.setAdapter(mPicMaterAdapter);
        mPicMaterAdapter.setOnItemClick(new AdapterOnItemClick<String>() {
            @Override
            public void onItemClick(String s, int position) {
                if (TextUtils.isEmpty(s)) {
                    isDevicePic = false;
                    mModel.pictureSelector(mPicMaterAdapter.hasCount());
                } else {
                    Intent intent = new Intent(getActivity(), PhotoViewActivity.class);
                    intent.putExtra(PhotoViewActivity.KEY_PHOTO_URLS, (Serializable) mPicMaterAdapter.getDatas());
                    intent.putExtra(PhotoViewActivity.KEY_PHOTO_POSITION, position);
                    startActivity(intent);
                }
            }
        });
    }

    private void initVideo() {
        mVideoAdapter = new SelfTeamVideoAdapter(this, new ArrayList<>(), 1);
        mBind.rvVideo.setLayoutManager(new GridLayoutManager(this, 4));
        mBind.rvVideo.setHasFixedSize(false);
        mBind.rvVideo.addItemDecoration(new GridSpacingItemDecoration(5, ScreenUtils.dip2px(this, 2), false));
        mBind.rvVideo.setAdapter(mVideoAdapter);
        mVideoAdapter.setOnItemClick(new AdapterOnItemClick<String>() {
            @Override
            public void onItemClick(String s, int position) {
                if (TextUtils.isEmpty(s)) {
                    mModel.videoSelector(mVideoAdapter.hasCount());
                } else {
                    PictureSelector.create(SelfTeamDeviceEditActivity.this).externalPictureVideo(s);
                }
            }
        });
    }

    @Override
    protected void init() {
        if (!TextUtils.isEmpty(id)) {
            mModel.detailEquipment(id);
        }
    }

    @Override
    public void onClick(View v) {
        int vId = v.getId();
        if (vId == R.id.btn_release) {
            if (TextUtils.isEmpty(mBind.etName.getContent())) {
                MToast.showToast(this, mBind.etName.getContent_edt().getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(mBind.etModelNum.getContent())) {
                MToast.showToast(this, "请输入设备数量");
                return;
            }
            if ("0".equals(mBind.etModelNum.getContent())) {
                MToast.showToast(this, "设备数量大于0");
                return;
            }
            if (TextUtils.isEmpty(mBind.etDes.getEditContent())) {
                MToast.showToast(this, mBind.etDes.getEditText().getHint().toString());
                return;
            }
            if (mPicAdapter.getRealCount() == 0) {
                MToast.showToast(this, "请上传设备图片");
                return;
            }

            if (mNewTextAdapter.getDatas().size() != 0) {
                checkAdapterData();
                if (isEmt) {
                    return;
                }
                mEntity.setNewFiledArr(mNewTextAdapter.getDatas());
            } else {
                mEntity.setNewFiledArr(null);
            }
            mEntity.setTitle(mBind.etName.getContent());
            mEntity.setModel(mBind.etModel.getContent());
            mEntity.setCountNum(mBind.etModelNum.getContent());
            mEntity.setDescribe(mBind.etDes.getEditContent());
            mEntity.setYears(mBind.etDeviceAge.getContent());
            mEntity.setFeatures(mBind.etFunction.getEditContent());

            mUploadImgList.clear();
            mUploadImgList2.clear();
            mCurPicNum = -1;
            mCurPicNum2 = -1;
            uploadPic();
        } else if (vId == R.id.add_btn) {
            if (mNewTextAdapter.getDatas().size() < 3) {
                addNewText();
            } else {
                MToast.showToast(this, "最多只能新增三个字段");
            }
        }
    }

    private void addNewText() {
        if (mBind.desList.getVisibility() == View.GONE) {
            mBind.desList.setVisibility(View.VISIBLE);
        }
        SelfEmploymentEditEntity.NewText emtData;
        List<SelfEmploymentEditEntity.NewText> EMTList;
        emtData = new SelfEmploymentEditEntity.NewText();
        emtData.setContent("");
        emtData.setName("");
        EMTList = new ArrayList<>();
        EMTList.add(emtData);
        mNewTextAdapter.addDatas(EMTList);
        mNewTextAdapter.upDate();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                if (isDevicePic) {
                    mPicAdapter.setPicData(selectList);
                } else {
                    mPicMaterAdapter.setPicData(selectList);
                }
            } else if (requestCode == PictureConfig.TYPE_VIDEO) {
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                mModel.uploadVideo(selectList.get(0).getRealPath());
            }
        }
    }

    private void uploadPic() {
        mCurPicNum++;
        int size = mPicAdapter.getRealCount();
        if (size > 0 && mCurPicNum < size) {
            String path = mPicAdapter.getDatas().get(mCurPicNum);
            if (path.startsWith("http")) {
                // 保存已上传图片
                mUploadImgList.add(path);
                uploadPic();
            } else {
                // 过滤已上传的
                if (!TextUtils.isEmpty(mCacheImgMap.get(path))) {
                    mUploadImgList.add(mCacheImgMap.get(path));
                    uploadPic();
                } else {
                    File file = new File(mPicAdapter.getDatas().get(mCurPicNum));
                    mModel.uploadMultiFileModel(file, mCurPicNum + 1, size, true);
                }
            }
        } else {
            uploadPic2();
        }
    }

    private void uploadPic2() {
        mCurPicNum2++;
        int size = mPicMaterAdapter.getRealCount();
        if (size > 0 && mCurPicNum2 < size) {
            String path = mPicMaterAdapter.getDatas().get(mCurPicNum2);
            if (path.startsWith("http")) {
                // 保存已上传图片
                mUploadImgList2.add(path);
                uploadPic2();
            } else {
                // 过滤已上传的
                if (!TextUtils.isEmpty(mCacheImgMap2.get(path))) {
                    mUploadImgList2.add(mCacheImgMap2.get(path));
                    uploadPic2();
                } else {
                    File file = new File(mPicMaterAdapter.getDatas().get(mCurPicNum2));
                    mModel.uploadMultiFileModel(file, mCurPicNum2 + 1, size, false);
                }
            }
        } else {
            release();
        }
    }

    public void release() {
        StringBuilder sb = new StringBuilder();
        if (mUploadImgList.size() > 0) {
            for (int i = 0; i < mUploadImgList.size(); i++) {
                sb.append(mUploadImgList.get(i));
                if (i < mUploadImgList.size() - 1) {
                    sb.append(",");
                }
            }
        }
        mEntity.setPicture(sb.toString());
        StringBuilder sb2 = new StringBuilder();
        if (mUploadImgList2.size() > 0) {
            for (int i = 0; i < mUploadImgList2.size(); i++) {
                sb2.append(mUploadImgList2.get(i));
                if (i < mUploadImgList2.size() - 1) {
                    sb2.append(",");
                }
            }
        }
        mEntity.setEvidencesImg(sb2.toString());
        mModel.addEquipment(mEntity);
    }

    // 图片上传回调
    public void uploadPicInfo(String fromString, String toString, boolean isDevice) {
        if (isDevice) {
            mUploadImgList.add(toString);
            mCacheImgMap.put(fromString, toString);
            uploadPic();
        } else {
            mUploadImgList2.add(toString);
            mCacheImgMap2.put(fromString, toString);
            uploadPic2();
        }
    }

    // 更新视频
    public void updateVideoInfo(String videoId, String filePath) {
        runOnUiThread(() -> {
            DialogHelper.dismissProgressDialog();
            mUploadVideoList.clear();
            mUploadVideoList.add(videoId);
            List<String> temps = new ArrayList<>();
            temps.add(filePath);
            mVideoAdapter.setData(temps);
        });
    }

    public void updateEntity(SelfTeamDeviceEntity data) {
        if (data != null) {
            mEntity = data;
            mBind.setViewModel(data);
            // 更新设备图片
            List<String> tempData = new ArrayList<>();
            if (!TextUtils.isEmpty(mEntity.getPicture())) {
                tempData.addAll(Arrays.asList(mEntity.getPicture().split(",")));
            }
            mPicAdapter.setData(tempData);
            // 更新证明材料图片
            List<String> tempData2 = new ArrayList<>();
            if (!TextUtils.isEmpty(mEntity.getEvidencesImg())) {
                tempData2.addAll(Arrays.asList(mEntity.getEvidencesImg().split(",")));
            }
            mPicMaterAdapter.setData(tempData2);
            if (data.getNewFiledArr() != null && data.getNewFiledArr().size() != 0) {
                mNewTextAdapter.addDatas(data.getNewFiledArr());
                if (mBind.desList.getVisibility() == View.GONE) {
                    mBind.desList.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    public void editEntitySuccess() {
        setResult(RESULT_OK, new Intent());
        finish();
    }

    public void showEmpty() {
        mBind.emptyView.setVisibility(View.VISIBLE);
        DialogHelper.dismissProgressDialog();
    }

    private List<PickSelectEntity> pickEquipmentConfig;
    private List<PickSelectEntity> propertyStatus;

    public void showEquipmentConfigPop(List<PickSelectEntity> list) {
        if (null == pickEquipmentConfig) {
            pickEquipmentConfig = new ArrayList<>();
            pickEquipmentConfig.addAll(list);
        }
        if (pickEquipmentConfig.size() > 0) {
            OptionsPickerView projectCategoryOption = new OptionsPickerBuilder(SelfTeamDeviceEditActivity.this, (options1, options2, options3, v) -> {
                mBind.etName.setContent(pickEquipmentConfig.get(options1).getProjectscale());
                mEntity.setName(pickEquipmentConfig.get(options1).getProjectscale());
            }).setCancelColor(ContextCompat.getColor(this, R.color.color_666666)).setTitleColor(ContextCompat.getColor(this, R.color.color_969696)).build();
            projectCategoryOption.setPicker(pickEquipmentConfig);
            projectCategoryOption.setTitleText("请选择设备名称");
            projectCategoryOption.setSelectOptions(0);
            projectCategoryOption.show();
        }
    }


    public void propertyStatusPop(List<PickSelectEntity> list) {
        if (list.size() > 0) {
            OptionsPickerView projectCategoryOption = new OptionsPickerBuilder(SelfTeamDeviceEditActivity.this, (options1, options2, options3, v) -> {
                mBind.etPropertyState.setContent(propertyStatus.get(options1).getProjectscale());
                mEntity.setStatus(propertyStatus.get(options1).getNo());
            }).setCancelColor(ContextCompat.getColor(this, R.color.color_666666)).setTitleColor(ContextCompat.getColor(this, R.color.color_969696)).build();
            projectCategoryOption.setPicker(propertyStatus);
            projectCategoryOption.setTitleText("请选择资产状态");
            projectCategoryOption.setSelectOptions(0);
            projectCategoryOption.show();
        }
    }

    @Override
    public void OnWholeItemClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.et_name) {
            if (null == pickEquipmentConfig) {
                mModel.getEquipmentConfig();
            } else {
                showEquipmentConfigPop(pickEquipmentConfig);
            }
        } else if (viewId == R.id.et_device_age) {
            showCourseTimePop();
        } else if (viewId == R.id.et_property_state) {
            if (null == propertyStatus) {
                propertyStatus = new ArrayList<>();
                propertyStatus.add(new PickSelectEntity("0", "闲置"));
                propertyStatus.add(new PickSelectEntity("1", "使用"));
            }
            propertyStatusPop(propertyStatus);
        }
    }

    private void checkAdapterData() {
        for (int i = 0; i < mNewTextAdapter.getDatas().size(); i++) {
            if ("".equals(mNewTextAdapter.getDatas().get(i).getName())) {
                MToast.showToast(this, "请输入字段名称");
                isEmt = true;
                return;
            } else if ("".equals(mNewTextAdapter.getDatas().get(i).getContent())) {
                MToast.showToast(this, "请输入字段内容");
                isEmt = true;
                return;
            } else {
                isEmt = false;
            }
        }
    }
}
